from django.db import models
import datetime, time

# Create your models here.

#tmp user
class User(models.Model):
    username = models.CharField(max_length = 32)
    nick = models.CharField(max_length = 128)
    email = models.EmailField()
    pwd = models.CharField(max_length = 32)
    
    def __unicode__(self):
        return self.username

    @staticmethod
    def get_usr(id):
        return User.objects.filter(pk = id)
    
class Word(models.Model):
    name = models.CharField(max_length = 32)
    user = models.ForeignKey(User)
    description = models.CharField(max_length = 256)
    comment_nb = models.IntegerField(default = 0)
    comment_sb = models.IntegerField(default = 0)
    comment_not_known = models.IntegerField(default = 0)
    rate = models.FloatField(default = 0)
    img_url = models.URLField(blank = True)
    created_at = models.DateTimeField()
    updated_at = models.DateTimeField(auto_now = True)
    
    def __unicode__(self):
        return self.name
    
    def click_nb(self):
        self.comment_nb += 1
        self.save()
        
    def click_sb(self):
        self.comment_sb += 1
        self.save()
        
    def click_not_known(self):
        self.comment_not_known += 1
        self.save()
        
    def get_rate(self):
        #TODO later, more accurately calculate
        rate = self.comment_nb + self.comment_not_known + self.comment_sb
        return rate
    
    @staticmethod
    def get_word_by_id(id):
        return Word.objects.filter(pk = id)
    
    @staticmethod
    def get_top10_list():
        return Word.objects.raw("SELECT * FROM fc_word order by (comment_nb + comment_sb + comment_not_known) limit 10")
    
class Comment(models.Model):
#    word = models.ForeignKey(Word)
#    text = models.CharField(max_length=280)
    user = models.ForeignKey(User)
    word = models.ForeignKey(Word)
    comment_nb = models.IntegerField(default=0)
    comment_sb = models.IntegerField(default=0)
    shared = models.IntegerField(default=0)
    content = models.CharField(max_length=280)
    type = models.IntegerField(default=0)
    created_at = models.DateTimeField()
    #replied_comment = models.ForeignKey(Comment)
    
    class meta:
        ordering = ['-created_at']
    
    def __unicode__(self):
        return self.content
    
    @staticmethod
    def comment_sum(word_loaded):
        print Comment.objects.filter(word=word_loaded)
        return Comment.objects.filter(word=word_loaded).count()
    
    @staticmethod
    def load_comments(word_loaded, start, count):
        return Comment.objects.filter(word=word_loaded).order_by('-created_at')[start:count]
    